

import { IResBundle } from "./IResBundle";
import { LoadItem } from "./LoadItem";
import { ResType, IResItem } from "./ResDefine";


export default class ResItem extends LoadItem implements IResItem {

    protected helper: IResBundle;

    //使用次数
    protected useCount: number = 0;

    //资源本身
    private res: any;


    //尝试加载次数
    private loadCount: number = 0;
    //加载是否结束
    protected _isDone: boolean = false;

    //是否加载完毕
    isDone() {
        return this._isDone;
    }

    /**
     * 加载完成调用
     * @param flag 
     */
    setLoadingFlag(flag: boolean) {
        this._isDone = flag;
    }

    //获得加载次数
    getLoadCount() {
        return this.loadCount;
    }
    //更新加载次数
    updateLoadCount() {
        this.loadCount++;
    }

    constructor(helper: IResBundle, url: string, type: ResType, bundle: string) {
        super(url, type, bundle);
        this.helper = helper;
    }

    get refCount() {
        return this.getUseCount();
    }


    getRes(): any {
        if (this.res) {
            this.addCount();
        }
        return this.res;
    }


    /**
     * 由于引擎加载机制，加载完成就已经使用，
     */
    setRes(res: any) {
        this.res = res;
        //加载成功后直接加1，以免被其他模块的记载器清理掉。自己主动调用一下getRes即可解决此问题
        //比如在loading界面加载的资源，没有使用，很容就被清楚了。所以这里可以尝试加1。
        this.addCount()

    }


    //获得使用次数
    getUseCount() {
        return this.useCount;
    }

    release() {
        this.showReCont();
        while (this.useCount > 0) {
            this.subCount();
        }
    }



    showReCont() {
        let hasCount = this.helper.resCount(this.res);

        if (hasCount != this.useCount) {

        }
    }



    subCount() {
        if (this.useCount > 0) {
            this.useCount--;
            this.helper.decRes(this.res)
        }


    }


    addCount() {
        this.useCount++;
        this.helper.addRes(this.res)
    }


}